const express = require('express')
const app = express()
const joi = require('joi')

// 跨域
const cors = require('cors')
app.use(cors())

// 处理application/x-www-form-urlencoded格式的表单数据
app.use(express.urlencoded({ extended: false }));

// 路由之前封装发送方法
app.use((req, res, next) => {
    res.s = function(err, status =1 ) {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

const userRouter = require('./router/user')
app.use('/api', userRouter)

// 全局错误中间件
app.use((err, req, res, next) => {
    // 验证失败的错误
    if(err instanceof joi.ValidationError) {
        res.s(err)
    }
    // 未知的错误
    res.s(err)
})

app.listen(3000, (req, res) => {
    console.log('api server running at http:127.0.0.1:3000')
})